#include <SDL.h>
#include <SDL_ttf.h>

int PrintStrings(SDL_Surface *sDest, TTF_Font *font, char *str, SDL_Rect *rc, SDL_Color clrFg, SDL_Color clrBg) {
    int lineSkip = TTF_FontLineSkip(font);  // Get the line-skip value.
    int width = 0, height = 10;
    char vLines[32][80], *p, *q;
    int line_count = 0, l, i;
    SDL_Surface *sText;
    SDL_Rect tempRect;
  
    // Break the string into its lines:
    for (p = str, q = strchr(str, '\n'); q; p = q + 1, q = strchr(p, '\n')) {
        l = q - p;
        if (l > 79) l = 79;
        memset(vLines[line_count], 0, 80);
        strncpy(vLines[line_count], p, l);
        
        // Get the size of the rendered text, mainly for the width
        int w = 0;
        TTF_SizeText (font, vLines[line_count++], &w, &height);
        if (w > width) {
            width = w;
        }
    }
    memset(vLines[line_count], 0, 80);
    strncpy(vLines[line_count], p, 79);
    int w = 0;
    TTF_SizeText (font, vLines[line_count++], &w, &height);
    if (w > width) {
        width = w;
    }

    // Determine the height, which is the height of the first line, plus the height plus line
    // spacings (the lineSkip value) of the subsequent lines
    height += (line_count - 1) * lineSkip;
    // (we assume that height is the same for all lines.)

    // Make the surface to which to blit the text:
    sText = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 
                                 sDest->format->BitsPerPixel, 
                                 sDest->format->Rmask,
                                 sDest->format->Gmask,
                                 sDest->format->Bmask,
                                 sDest->format->Amask);
    // (it's compatible with the destination Surface

    // Now, fill it with the background color:
    SDL_FillRect(sText, NULL, (clrBg.r<<24) | (clrBg.g<<16) | (clrBg.b<<8));

    // Actually render the text:
    SDL_Surface *sTemp = NULL;
    for (i = 0; i < line_count; i++) {
        // The rendered text:
        sTemp = TTF_RenderText_Solid(font, vLines[i], clrFg);
        if (sTemp == NULL) {
            fprintf(stderr, "Unable to render text \"%s\": %s\n", vLines[i], SDL_GetError());
            exit(1);
        }
    
        // Put it on the surface (sText):
        tempRect.x = 0;
        tempRect.y = i*lineSkip;
        tempRect.w = 0;
        tempRect.h = 0;
        SDL_BlitSurface(sTemp, NULL, sText, &tempRect);
        // Clean up:
        SDL_FreeSurface( sTemp );
    }
    // So, now we have a nice bitmap (sText) that has all the text on it.

    // Draw the text on the destination:
    SDL_BlitSurface(sText, NULL, sDest, rc);
    SDL_FreeSurface(sText);
    return width;
}
